package com.jemmyee.pizza.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.DateUtils;
import com.jemmyee.pizza.entity.Card;
import com.jemmyee.pizza.entity.Excerpt;
import com.jemmyee.pizza.entity.Message;
import com.jemmyee.pizza.entity.Person;
import com.jemmyee.pizza.service.ICardService;
import com.jemmyee.pizza.service.IExcerptService;
import com.jemmyee.pizza.service.IMessageService;
import com.jemmyee.pizza.service.IPersonService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.bean.ExcerptBean;
import com.jemmyee.pizza.web.bean.SurrogateBean;
import com.jemmyee.pizza.web.utils.SendMessageUtils;

/**
 * @author qiuchao
 * 2010-12-21
 */
@Controller
@RequestMapping("/admin/excerpt")
public class ExcerptController {
	@Autowired
	private IExcerptService excerptService;
	@Autowired
	private IPersonService<Person> personService;
	@Autowired
	private ICardService<Card> cardService;
	@Autowired
	private IMessageService messageService;
	
	@RequestMapping("/list/{from}/{startIndex}")
	public ModelAndView list(@PathVariable Integer startIndex,@PathVariable String from,@ModelAttribute ExcerptBean bean,HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Excerpt.class);
		ExcerptBean excerptBean = new ExcerptBean();
		String name = "";
		String number = "";
		String type = "";
		String status = "";
		String startTime = "";
		String endTime = "";
		if (from.equals("form")) {
			excerptBean = bean;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, excerptBean);
		}
		if (from.equals("page")) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				excerptBean = (ExcerptBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
		}
		if (from.equals("menu")) {
			System.out.println("menu is call");
		}
		
		if(excerptBean.getName() != null && !excerptBean.getName().equals("")){
			dc.add(Restrictions.like("personName", excerptBean.getName(), MatchMode.ANYWHERE));
			name = " and person_name like '%"+excerptBean.getName()+"%'";
		}
		
		if(excerptBean.getNumber() != null && !excerptBean.getNumber().equals("")){
			dc.add(Restrictions.like("personNumber", excerptBean.getNumber(), MatchMode.ANYWHERE));
			number = " and person_number like '%"+excerptBean.getNumber()+"%'";
		}
		
		if(excerptBean.getType() != null && !excerptBean.getType().equals("")){
			dc.add(Restrictions.eq("gasType", excerptBean.getType()));
			type = " and gas_type = "+excerptBean.getType();
		}
		
		if(excerptBean.getStatus() != null && !excerptBean.getStatus().equals("")){
			dc.add(Restrictions.eq("payStatus", excerptBean.getStatus()));
			status = " and pay_status = "+excerptBean.getStatus();
		}
		// 发布时间
		if (excerptBean.getStartTime() != null && !excerptBean.getStartTime().equals("")) {
			dc.add(Restrictions.ge("excerptTime", excerptBean.getStartTime()));
			System.out.println(DateUtils.formatDateTime(DateUtils.parseDateToString(excerptBean.getStartTime())));
			startTime = " and excerpt_time >= '"+DateUtils.formatDateTime(DateUtils.parseDateToString(excerptBean.getStartTime()))+"'";
		}
		if (excerptBean.getEndTime() != null && !excerptBean.getEndTime().equals("")) {
			dc.add(Restrictions.le("excerptTime", excerptBean.getEndTime()));
			endTime = " and excerpt_time <= '"+DateUtils.formatDateTime(DateUtils.parseDateToString(excerptBean.getEndTime()))+"'";
		}

//		dc.addOrder(Order.desc("excerptTime"));
		ModelAndView mv = new ModelAndView();
		Page page = excerptService.findPageByCriteria(dc,Constants.DEFAULT_PAGESIZE, startIndex,"excerptTime");
		
		String sql_1 = "select count(excerpt_id),case when sum(gas_amount) is null then 0 else sum(gas_amount) end,case when sum(gas_money) is null then 0 else sum(gas_money) end," +
			"(select case when sum(gas_money) is null then 0 else sum(gas_money) end from (select top "+Constants.DEFAULT_PAGESIZE+" * from Excerpt where excerpt_id not in (select top "+startIndex +" excerpt_id from Excerpt) "+name+number+type+status+startTime+endTime+" order by excerpt_time desc) as s1 where pay_status=0 )," +
			"(select case when sum(gas_money) is null then 0 else sum(gas_money) end from (select top "+Constants.DEFAULT_PAGESIZE+" * from Excerpt where excerpt_id not in (select top "+startIndex +" excerpt_id from Excerpt) "+name+number+type+status+startTime+endTime+" order by excerpt_time desc) as s2 where pay_status=1) from (select top "+Constants.DEFAULT_PAGESIZE+" * from Excerpt where excerpt_id not in (select top "+startIndex +" excerpt_id from Excerpt) "+name+number+type+status+startTime+endTime+" order by excerpt_time desc) as s3";
		
		String sql_2 = "select count(excerpt_id),case when sum(gas_amount) is null then 0 else sum(gas_amount) end,case when sum(gas_money) is null then 0 else sum(gas_money) end," +
			"(select case when sum(gas_money) is null then 0 else sum(gas_money) end from Excerpt where 1=1"+name+number+type+status+startTime+endTime+" and pay_status=0)," +
			"(select case when sum(gas_money) is null then 0 else sum(gas_money) end from Excerpt where 1=1"+name+number+type+status+startTime+endTime+" and pay_status=1) from Excerpt where 1=1"+name+number+type+status+startTime+endTime+"";

		mv.addObject("SurrogateStatistic_1", excerptService.getExcerptStatisticByTerm(sql_1));
		mv.addObject("SurrogateStatistic_2", excerptService.getExcerptStatisticByTerm(sql_2));
		mv.addObject("page", page);
		mv.addObject("excerptBean", excerptBean);
		mv.setViewName("/admin/excerpt/list");
		return mv;
	}
	
	@RequestMapping("/to_pay_money/{id}")
	public ModelAndView toPayMoney(@PathVariable Integer id) {
		ModelAndView mv = new ModelAndView();
		Excerpt excerpt = excerptService.findById(id);
		mv.addObject("excerpt", excerpt);
		mv.setViewName("/admin/excerpt/pay_money");
		return mv;
	}
	
	@RequestMapping("/pay_money/{excerptId}/{cardId}/{cardNumber}/{payWise}")
	@ResponseBody
	public Map<String, Object> payMoney(@PathVariable Integer excerptId,@PathVariable Integer cardId,@PathVariable String cardNumber,@PathVariable Integer payWise) {
		Map<String, Object> model = new HashMap<String, Object>();
		if(excerptId != null && payWise != null){
			if((payWise == 0 || payWise == 1)&& cardId == null){
				Excerpt excerpt = excerptService.findById(excerptId);
				if(excerpt != null){
					excerpt.setPayStatus(1);
					excerpt.setPayWise(payWise);
					excerpt.setPayTime(new Date());
					excerptService.update(excerpt);
					model.put("msg", "succ");
				}else{
					model.put("msg", "error");
				}
			}else if(payWise == 2 && cardId != null){
				Card card = cardService.findById(cardId);
				Excerpt excerpt = excerptService.findById(excerptId);
				if(card != null && excerpt != null && (card.getMoney()==null?0:card.getMoney()) >= excerpt.getGasMoney()){
					card.setMoney((card.getMoney()==null?0:card.getMoney())-excerpt.getGasMoney());
					card.setCardNumber(cardNumber);
					cardService.update(card);
					
					excerpt.setPayStatus(1);
					excerpt.setPayWise(payWise);
					excerpt.setPayTime(new Date());
					excerptService.update(excerpt);
					
					model.put("msg", "succ");
				}else{
					model.put("msg", "error");
				}
			}else{
				model.put("msg", "error");
			}
		}else{
			model.put("msg", "error");
		}
		return model;
	}
	
	@RequestMapping("/get_card_list/{number}")
	@ResponseBody
	public Map<String, Object> getCardList(@PathVariable String number) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<Person> personList = personService.findByProperty("personNumber", number);
		if(personList != null && personList.size() > 0){
			List<Card> cardList = cardService.findByProperty("personId", personList.get(0).getPersonId());
			model.put("msg","succ");
			StringBuffer sb = new StringBuffer();
			sb.append("<table border=\"0\" cellpadding=\"\" cellspacing=\"1\" align=\"center\" width=\"92%\" id=\"web_tab\">");
			sb.append("<tr>");
			sb.append("<td width=\"40%\">卡号</td>");
			sb.append("<td width=\"20%\">余额</td>");
			sb.append("<td width=\"20%\">操作</td>");
			sb.append("</tr>");
			sb.append("<tr>");
			if(cardList != null && cardList.size() > 0){
				for(Card card : cardList){
					sb.append("<td>"+card.getCardNumber()+"</td>");
					sb.append("<td>"+(card.getMoney()==null?0:card.getMoney())+"</td>");
					sb.append("<td><input type=\"button\" class=\"but\" value=\"选择\" onclick=\"set_card_number('"+card.getCardId()+"','"+card.getCardNumber()+"','"+(card.getMoney()==null?0:card.getMoney())+"')\"/></td>");
					sb.append("</tr>");
					sb.append("<tr>");
				}
			}else{
				sb.append("<td colspan=\"3\" align=\"center\">此用户尚未添加卡信息</td>");
				sb.append("</tr>");
				sb.append("<tr>");
			}
			sb.append("<td colspan=\"3\" align=\"center\"><input type=\"button\" class=\"but\" value=\"关闭\" onclick=\"hidePopup();\"></td>");
			sb.append("</tr>");
			sb.append("</table>");
			model.put("sb",sb);
		}else{
			model.put("msg","error");
		}
		return model;
	}
	
	@RequestMapping("/list_for_person/{from}/{startIndex}")
	public ModelAndView listForPerson(@PathVariable Integer startIndex,@PathVariable String from,@ModelAttribute ExcerptBean bean,HttpServletRequest request) {
		DetachedCriteria dc = DetachedCriteria.forClass(Excerpt.class);
		ExcerptBean excerptBean = new ExcerptBean();
		if (from.equals("form")) {
			excerptBean = bean;
			request.getSession().setAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN, excerptBean);
		}
		if (from.equals("page")) {
			if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
				excerptBean = (ExcerptBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
			}
		}
		
		if(excerptBean.getNumber() != null){
			dc.add(Restrictions.like("personNumber", excerptBean.getNumber(), MatchMode.ANYWHERE));
		}
		

		// 发布时间
		if (excerptBean.getStartTime() != null) {
			dc.add(Restrictions.ge("excerptTime", excerptBean.getStartTime()));
		}
		if (excerptBean.getEndTime() != null) {
			dc.add(Restrictions.le("excerptTime", excerptBean.getEndTime()));
		}

//		dc.addOrder(Order.desc("excerptTime"));
		ModelAndView mv = new ModelAndView();
		Page page = excerptService.findPageByCriteria(dc,Constants.DEFAULT_PAGESIZE, startIndex,"excerptTime");
		mv.addObject("page", page);
		mv.addObject("excerptBean", excerptBean);
		mv.setViewName("/admin/excerpt/list_for_person");
		return mv;
	}
	
	@RequestMapping("/send")
	public void send(HttpServletRequest request) throws Exception{
		ExcerptBean bean = new ExcerptBean();
		if (request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN) != null) {
			bean = (ExcerptBean) request.getSession().getAttribute(Constants.SESSION_PAGE_SYS_QUERY_BEAN);
		}
		if(bean != null){
			DetachedCriteria dc = DetachedCriteria.forClass(Excerpt.class);
			if(bean.getName() != null && !bean.getName().equals("")){
				dc.add(Restrictions.like("personName", bean.getName(), MatchMode.ANYWHERE));
			}
			if(bean.getNumber() != null && !bean.getNumber().equals("")){
				dc.add(Restrictions.like("personNumber", bean.getNumber(), MatchMode.ANYWHERE));
			}
			if(bean.getType() != null && !bean.getType().equals("")){
				dc.add(Restrictions.eq("gasType", bean.getType()));
			}
//			if(bean.getStatus() != null && !bean.getStatus().equals("")){
				dc.add(Restrictions.eq("payStatus", 0));
//			}
			// 发布时间
			if (bean.getStartTime() != null && !bean.getStartTime().equals("")) {
				dc.add(Restrictions.ge("excerptTime", bean.getStartTime()));
			}
			if (bean.getEndTime() != null && !bean.getEndTime().equals("")) {
				dc.add(Restrictions.le("excerptTime", bean.getEndTime()));
			}
			List<Excerpt> lt = excerptService.findByCriteria(dc);
			for(Excerpt excerpt : lt){
				String context = excerpt.getPersonName()+"您"+excerpt.getExcerptTime().toString().substring(0, 4)+"年"+excerpt.getExcerptTime().toString().substring(5, 7)+"月的燃气费用为"+excerpt.getGasMoney()+"。由于您的账户余额不足，扣费失败，请您尽快补缴欠费。----佳鸿燃气公司";
				Message message = new Message();
				message.setName(excerpt.getPersonName());
				message.setPhone(excerpt.getPersonPhone());
				message.setContext(context);
				message.setRemark(SendMessageUtils.send(excerpt.getPersonPhone(), context));
				message.setSendUserName((String)request.getSession().getAttribute(Constants.ONLINE_USERNAME));
				message.setSendTime(new Date());
				messageService.save(message);
			}
		}
		
	}
}
